var publish_way_is_memberArr = [];
var publish_way_is_member_nameArr = [];
define(function (require, exports, module) {

        //加载依赖
        //require("ajaxproxy");
    require("JTemplate");
    require("layer");
    //require('ztree');
    require('ztree-excheck');
    require("ztree-exedit");

    require('jquery-validate');
    require('validate');
    require('v-addmethod');


    var common = require("common");


    jQuery.validator.addMethod("isTure13", function (value, element) {
        if (value == '') {

            return true;
        }

        var r = /^(?!0+(\.0+)?$)\d+(\.\d{0,3})?$/;//三位浮点数或整数

        return r.test(value);

    }, "数量错误，最多保留三位小数");

    jQuery.validator.addMethod("isTure14", function (value, element) {
        if (value == '') {

            return true;
        }

        var r = /^(?!0+(\.0+)?$)\d+(\.\d{0,2})?$/;//两位浮点数或整数

        return r.test(value);

    }, "价格错误，最多保留两位小数");
    jQuery.validator.addMethod("isTure15", function (value, element) {
        var s1=$('input[name="data[publish_way]"]:checked').val();
        if (s1==2||s1==3) {

            if(value==''){

                return false;
            }else{

                return true;
            }
        }else{

            return true;


        }

    }, "指定会员价不能为空");
    jQuery.validator.addMethod("isTure17", function (value, element) {
       if(value>0){

           return true;
       }else{
           return false;
       }

    }, "请输入大于0的数");



    //member_sales_price
    exports.initByEdit = function () {
        this.initCommon();

        var arr7 = exports.tpfb.split('-');

        fixSelected(arr7[0], arr7[1], arr7[2], arr7[3]);//设置类型、品名、厂家、牌号select默认值

        var callback = function (data) {
            if(data.data==''){
                var inserthtml = '';
            }else{
                var address = data.data.address + '' + data.data.street;
                var inserthtml = '<div class="form-group">' +
                    '<label class="col-sm-2 control-label">联系人</label>' +
                    '<label class="col-sm-4 control-label my-left">' + data.data.contact + '</label>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="col-sm-2 control-label">联系电话</label>' +
                    '<label class="col-sm-4 control-label my-left">' + data.data.contact_mobile + '</label>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="col-sm-2 control-label">交收所在地</label>' +
                    '<label class="col-sm-4 control-label my-left">' + address + '</label>' +
                    '</div>';
            }


            $('#repertory_info').html(inserthtml);

        };
        getRepertory($('select[name="data[repertory_id]"]').val(), callback);

    };


    exports.initByAdd = function () {
        this.initCommon();

    };
    //初始化编辑器控件
    exports.editor = function (configs) {
        require("editor");
        KindEditor.ready(function (K) {
            K.create('.editor', {
                uploadJson : '/admin/upload/kindeditor_upload',
                fileManagerJson: '/admin/upload/kindeditor_upload',//?fileInputName=src
                allowFileManager: false,
                //imageUploadLimit : 20,
                imageSizeLimit: '1MB',
                afterBlur: function () {
                    this.sync();
                },
                afterChange : function() {
                    //$('.word_count1').html(this.count()); //字数统计包含HTML代码
                    //$('.word_count2').html(this.count('text'));  //字数统计包含纯文本、IMG、EMBED，不包含换行符，IMG和EMBED算一个文字
                    var limitNum = 5000;  //设定限制字数
                    var pattern = '还可以输入' + limitNum + '字';
                    $('.word_surplus').html(pattern); //输入显示
                    if(this.count('text') > limitNum) {
                        pattern = ('字数超过限制，请适当删除部分内容');
                        //超过字数限制自动截取
                        var strValue = this.text();
                        strValue = strValue.substring(0,limitNum);
                        this.text(strValue);
                    } else {
                        //计算剩余字数
                        var result = limitNum - this.count('text');
                        pattern = '还可以输入' +  result + '字';
                    }
                    $('.word_surplus').html(pattern); //输入显示
                }

            });

        });
    }

    exports.initCommon = function () {

        $('#content-add-form').validate({

            rules: {
                "data[type_name_id]": {//数量
                    required: true,
                },
                "data[pkg_size]": {//货品规格
                    required: true,
                    isTure17: true,
                },
                "data[quantity]": {//数量
                    required: true,
                    maxlength: 20,
                    minlength: 1,
                    isTure13: true
                },
                "data[min_volume]": {//最小交易量
                    required: true,
                    maxlength: 20,
                    minlength: 1,
                    isTure13: true
                },
                "data[sales_price]": {//销售价
                    required: true,
                    maxlength: 20,
                    minlength: 1,
                    isTure14: true
                },
                "data[cost_price]": {//成本价
                    maxlength: 20,
                    minlength: 1,
                    isTure14: true
                },
                "data[member_sales_price]": {//指定会员销售价
                    maxlength: 20,
                    minlength: 1,
                    isTure15: true
                },


            },
            messages: {
                "data[quantity]": {
                    required: "数量不能为空"

                },
            },
            submitHandler: function (form) {

                var formData = $('#' + $(form).attr('id')).serialize();

                common.ajaxResult($(form).attr('action'), formData, function () {
                    if(exports.success_return_link=='indexByStore'||$('input[name="data[status]"]').val()=='2'){
                        location.href = 'indexByStore';

                    }else{

                        location.href = 'indexBySale';

                    }
                });

                return false;

            }
        });
        //发布商品直接进入仓库
        $('.btn-add-repertory').click(function(){

             $('input[name="data[status]"]').val('2');

        });
        $('.btn-add-sale').click(function(){

            $('input[name="data[status]"]').val('1');

        });

        $('#content-add-form input,#content-add-form select').change(function () {

            getProductNo();
        });
        $('#content-add-form input,#content-add-form select').focus(function () {

            getProductNo();
        });

        $('select[name="data[repertory_id]"]').change(function () {
            var callback = function (data) {
                if(data.data==''){
                    var inserthtml = '';
                }else{
                    var address = data.data.address + '' + data.data.street;

                    var inserthtml = '<div class="form-group">' +
                        '<label class="col-sm-2 control-label">联系人</label>' +
                        '<label class="col-sm-4 control-label my-left">' + data.data.contact + '</label>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-sm-2 control-label">联系电话</label>' +
                        '<label class="col-sm-4 control-label my-left">' + data.data.contact_mobile + '</label>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-sm-2 control-label">交收所在地</label>' +
                        '<label class="col-sm-4 control-label my-left">' + address + '</label>' +
                        '</div>';
                }


                $('#repertory_info').html(inserthtml);

            };
            getRepertory($(this).val(), callback);

        });
        var myNodes='';
        $('input[name="data[publish_way]"]').click(function () {


            if($(this).val()==2||$(this).val()==3) {
                layer.open({
                    type: 1,
                    title: "指定会员",
                    area: ['800px', '500px'],
                    content: JTemplate.render("publish_way_is_members"),
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {


                        $("#member_form").validate().element('#member_sales_price');
                        if($("#checked_members_value").val() == ''){
                            $("#checked_members_value-error").show();
                            return false;
                        }else{

                            $("#checked_members_value-error").hide();
                        }

                        var member_sales_price = layero.find('input[name=member_sales_price]').val();

                        var member_delivery_way = layero.find('input[name=member_delivery_way]:checked').val();


                        var r = /^(?!0+(\.0+)?$)\d+(\.\d{0,2})?$/;//两位浮点数或整数
                        if(member_sales_price!=''&&!r.test(member_sales_price)){

                            layer.msg("价格错误，最多保留两位小数");
                            return ;

                        }


                        if($('#member_sales_price').val()!=''&&publish_way_is_member_nameArr.length>0){

                            $('input[name="data[member_sales_price]"]').val(member_sales_price);

                            $('input[name="data[member_delivery_way]"]').val(member_delivery_way);

                            member_delivery_way=(member_delivery_way==1)?'买家自提':'卖家配送';

                            var temp2 = '';
                            temp2 += '<tr style="background: #ccc;"><th style="width:100px;">会员名</th><th  style="width:100px;">销售价(元/吨)</th><th>交收方式</th></tr><tr><td>';
                            for (i in publish_way_is_member_nameArr) {

                                temp2 += '<tr><td>' + publish_way_is_member_nameArr[i] + '</td><td>' + member_sales_price + '</td><td>' + member_delivery_way + '</td></tr>';
                            }

                            $('.publish_way_is_members_name').html(temp2);
                            layer.closeAll();
                        }else{

                            $('.publish_way_is_members_name').html('');


                        }

                    },
                    success: function () {

                        var setting = {
                            check: {
                                enable: true
                            },
                            data: {
                                simpleData: {
                                    enable: true
                                }
                            },
                            callback: {
                                onCheck: function (treeId, treeNode) {
                                    setCheckRerult();
                                    return true;
                                },
                            }
                        };
                        $('input[name="member_sales_price"]').val($('input[name="data[member_sales_price]"]').val());

                        var tmp6=$('input[name="data[member_delivery_way]"]').val();

                        if(tmp6){
                            $("input[name=member_delivery_way][value="+tmp6+"]").attr("checked",true);

                        }


                        if(myNodes){
                            $.fn.zTree.init($("#treeDemo"), setting, myNodes);

                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                            treeObj.setting.check.chkboxType = {"Y": "ps", "N": "ps"};
                            myNodes=treeObj.getNodes();

                        }else{

                            var zNodes = exports.zNodes;
                            $.fn.zTree.init($("#treeDemo"), setting, zNodes);

                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                            treeObj.setting.check.chkboxType = {"Y": "ps", "N": "ps"};

                            myNodes=treeObj.getNodes();

                        }
                        //搜索树
                        $('.btn-tree-search').click(function(){

                            var ss=$('input[name=input-tree-search]').val();

                            var node = treeObj.getNodeByParam("name", ss, null);
                            if(node){

                                treeObj.selectNode(node);
                                treeObj.checkNode(node, true, true);
                                setCheckRerult();
                            }
                        });


                        setCheckRerult();

                    },
                    btn1: function () {//取消
                        layer.closeAll();
                    }
                });
            } else {

                $('.publish_way_is_members_name').html('');
            }


        });
    };
});

function setCheckRerult() {

    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getCheckedNodes();
    var nodesLen = nodes.length;
    var resultHtml = '<table style="width: 100%;">';
    publish_way_is_memberArr = [];
    publish_way_is_member_nameArr = [];
    for (var i = 0; i < nodesLen; i++) {
        if (nodes[i].level != 0) {
            publish_way_is_memberArr.push(nodes[i].id);
            publish_way_is_member_nameArr.push(nodes[i].name);
            resultHtml += '<tr><td>' + nodes[i].name + '</td><td>' + nodes[i].getParentNode().name + '</td></tr>';

        }
    }

    resultHtml += '</table>';

    $('input[name="data[publish_way_is_members]"]').val(publish_way_is_memberArr.join(','));
    $('#checked_members_value').val(publish_way_is_memberArr.join(','));
    if($("#checked_members_value").val() == ''){
        $("#checked_members_value-error").show();
        return false;
    }else{

        $("#checked_members_value-error").hide();
    }

    $('#checked_members').html(resultHtml);
}
function getRepertory(repertory_id, callback) {
    var url = "/admin/repertory/getRepertory?id=" + repertory_id + "&timestamp=" + new Date().getTime();
    $.getJSON(url, function (data) {
        callback(data);
    });
}

function setTpfb() {

    $("input[name='data[type_name]']").val($("select[name='data[type_name_id]']").find("option:selected").text());
    $("input[name='data[product_name]']").val($("select[name='data[product_name_id]']").find("option:selected").text());
    $("input[name='data[factory_name]']").val($("select[name='data[factory_name_id]']").find("option:selected").text());
    $("input[name='data[brand_name]']").val($("select[name='data[brand_name_id]']").find("option:selected").text());
    var type_name = $("select[name='data[type_name_id]']").val();
    var product_name = $("select[name='data[product_name_id]']").val();
    var factory_name = $("select[name='data[factory_name_id]']").val();
    var brand_name = $("select[name='data[brand_name_id]']").val();
    var pkg_size = $("input[name='data[pkg_size]']").val();
    $("input[name='data[tpfb]']").val(type_name + '-' + product_name + '-' + factory_name + '-' + brand_name);

}
//获取货号
function getProductNo() {

    var type_name = $("select[name='data[type_name_id]']").val();
    var product_name = $("select[name='data[product_name_id]']").val();
    var factory_name = $("select[name='data[factory_name_id]']").val();
    var brand_name = $("select[name='data[brand_name_id]']").val();
    var pkg_size = $("input[name='data[pkg_size]']").val();

    if(type_name!=''&&product_name!=''&&factory_name!=''&&brand_name!=''&&pkg_size!=''){


        setTpfb();
        var param = 'type_name=' + type_name + '&product_name=' + product_name + '&factory_name=' + factory_name + '&brand_name=' + brand_name + '&pkg_size=' + pkg_size;

        $.get('getProductNo?' + param, function (data) {
            if (data.code == 0) {
                $("input[name='data[product_no]']").val(data.data);
            }
        }, 'json');
    }else{

        $("input[name='data[product_no]']").val('');
    }


}


/* start 分类品名厂家牌号四级联动所用的*/
/**
 * 返回所有产品分类列表
 */

function getTypeList(callback) {
    var url = "/product/brand/type?timestamp=" + new Date().getTime();
    $.getJSON(url, function (data) {
        callback(data);
    });
}

/**
 * 通过产品分类ID取得品名列表
 * @param typeId 分类Id
 */
function getNameList(typeId, callback) {
    var url = "/product/brand/name?type_id=" + typeId + "&timestamp=" + new Date().getTime();
    $.getJSON(url, function (data) {

        callback(data);

    });
}
/**
 * 品名ID取得厂家列表
 * @param typeId 分类Id
 * @param productId 品名Id
 */
function getFactoryList(typeId, productId, callback) {
    var url = "/product/brand/factory?type_id=" + typeId + "&product_id=" + productId + "&timestamp=" + new Date().getTime();
    $.getJSON(url, function (data) {

        callback(data);
    });
}
/**
 * 按分类ID，品名ID,厂家取得牌号列表
 * @param typeId 分类Id
 * @param productId 品名Id
 * @param factoryId 品名Id
 */
function getBrandList(typeId, productId, factoryId, callback) {
    factoryId = encodeURI(factoryId);
    var url = "/product/brand/brand?timestamp=" + new Date().getTime() + "&type_id=" + typeId + "&product_id=" + productId + "&factory_id=" + factoryId;
    $.getJSON(url, function (data) {
        callback(data);
    });
}


function setValueInSelect(JQselector, firstOption, optionValueParamName, optionHtmlParamName, data, defaultOption) {

    JQselector.html("<option value='' >" + firstOption + "</option>");

    JQselector.append(function () {
        var s = "";

        $(data).each(function (index, el) {
            if (optionValueParamName == 'brandId') {

                s = s + "<option data-brand-id='" + el.id + "' value='" + el.id + "'>" + el.name + "</option>"

            } else {

                s = s + "<option value='" + el.id + "'>" + el.name + "</option>"

            }

        });
        return s;
    });

    if (defaultOption) {
        JQselector.find("[value='" + defaultOption + "']").attr("selected", "selected");
        if (optionHtmlParamName == 'brandNumber') {
            var bra_id = $("input[name='brand_id']");

            bra_id.val(JQselector.find("option:selected").attr('data-brand-id'));
        }
    }

}

/* end 分类品名厂家牌号四级联动所用的函数*/

//自动化的四级联动，用#fourLinkage包裹所有的select
/**
 *分类class select_type
 *品名class select_pro
 *厂家class
 *
 **/

if ($("#fourLinkage").length > 0) {
    var typ = $(".select_type");
    getTypeList(function (data) {
        setValueInSelect(typ, "请选择类型", "typeId", "name", data)
    });
}
/**产品分类的四级联动*/
$("#fourLinkage select").on("change", function () {
    if (this.value != '' || this.value == '') {
        var typ = $(".select_type").not(".select2-container");
        var pro = $(".select_pro").not(".select2-container");
        var fac = $(".select_fac").not(".select2-container");
        var bra = $(".select_bra").not(".select2-container");
        var getMethodName;
        var JQthisEl = $(this);
        if (JQthisEl.hasClass("select_type")) {

            getMethodName = "getNameList(typ.find(':selected').val(),function(data){" +
                "setValueInSelect(pro,'请选择品名','productId','name',data);" +
                "setValueInSelect(fac,'请选择厂家','factoryId','name',null);" +
                "setValueInSelect(bra,'请选择牌号','brandId','name',null);" +
                "})";

        }
        else if (JQthisEl.hasClass("select_pro")) {
            getMethodName = "getFactoryList(typ.find(':selected').val(),pro.find(':selected').val(),function(data){" +
                "setValueInSelect(fac,'请选择厂家','factoryId','factoryId',data);" +
                "setValueInSelect(bra,'请选择牌号','brandId','brandId',null);})"

        }
        else if (JQthisEl.hasClass("select_fac")) {
            getMethodName = "getBrandList(typ.find(':selected').val(),pro.find(':selected').val(),fac.find(':selected').val(),function(data){setValueInSelect(bra,'请选择牌号','brandId','brandId',data);})"

        }
        else if (JQthisEl.hasClass("select_bra")) {
            var bra_id = $("input[name='data[brand_id]']");

            bra_id.val($(".select_bra").find("option:selected").attr('data-brand-id'));


        }
        eval(getMethodName);

    }
});

function fixSelected(product_type, product_number, factory_name, brand_number) {

    if ($("#fourLinkage").length > 0) {

        var typ = $(".select_type").not(".select2-container");
        var pro = $(".select_pro").not(".select2-container");
        var fac = $(".select_fac").not(".select2-container");
        var bra = $(".select_bra").not(".select2-container");

        getTypeList(function (data) {

            setValueInSelect(typ, "--请选择类型--", "typeId", "name", data, product_type);

            getNameList(product_type, function (data) {

                setValueInSelect(pro, "--请选择品名--", "productId", "name", data, product_number);

                getFactoryList(product_type, product_number, function (data) {

                    setValueInSelect(fac, "--请选择厂家--", "factoryId", "name", data, factory_name);

                    getBrandList(product_type, product_number, factory_name, function (data) {
                        setValueInSelect(bra, "--请选择牌号--", "brandId", "name", data, brand_number);

                        setTpfb();
                    });

                });
            });
        });

    }
}
